package com.gemini.main.concurrent;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 高效的缓存写法
 * @see java.util.concurrent.ConcurrentHashMap#putIfAbsent(Object, Object)
 * @see FutureTask
 * @param <A>
 * @param <V>
 */
public class EffectiveMemoizer<A, V> implements Computable<A, V> {

    private final Map<A, Future<V>> cache
            = new ConcurrentHashMap<A, Future<V>>();
    private final Computable<A, V> c;


    public EffectiveMemoizer(Computable<A, V> c) {
        this.c = c;
    }
    @Override
    public V compute(A arg) throws InterruptedException {
        while (true) {
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> eval = () -> c.compute(arg);
                FutureTask<V> ft = new FutureTask<V>(eval);
                //如果传入key对应的value已经存在，就返回存在的value，不进行替换。如果不存在，就添加key和value，返回null
                f = cache.putIfAbsent(arg, ft);
                if (f == null) {
                    f = ft;
                    ft.run();
                }
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                cache.remove(arg, f);
            } catch (ExecutionException e) {
                //throw LaunderThrowable.launderThrowable(e.getCause());
            }
        }
    }
}
